package dbhandler;

import javafx.beans.binding.ObjectExpression;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Sql {
    private Connection conn;

    //给连接赋值
    public Sql(Connection conn){
        this.conn=conn;
    }

    //增删改
    public int Update(String sql,Object...param) throws SQLException{
        if(conn==null){
            throw new SQLException("没有sql");
        }

        if (sql==null){
            throw new SQLException("没有sql");
        }
        if (param==null){
            throw new SQLException("没有参数");
        }
        PreparedStatement ps=null;
        //执行sql语句
         ps=conn.prepareStatement(sql);
        setParam(ps,param);
        //有几条数据发生了变化
        int i = ps.executeUpdate();
        return i;
    }



    //查询
    public <T> T executeQuery(String sql,ResultSetHandler<T> handler,Object...param) throws SQLException {
        if (conn==null){
            throw new SQLException("没有conn连接");
        }

        if (sql==null){
            throw new SQLException("没有sql语句");
        }

        if (handler==null){
            throw new SQLException("没有handler");
        }

        PreparedStatement ps=null;
        ResultSet rs=null;
        T t=null;

        ps=conn.prepareStatement(sql);
        setParam(ps,param);
        rs = ps.executeQuery();
        t = handler.handler(rs);
        return t;
    }

    private void setParam(PreparedStatement ps,Object...param) throws SQLException {
        for (int i=0;i<param.length;i++){
            ps.setObject(i+1,param[i]);
        }
    }

}
